package com.lan3g.Test.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCUtil {
    private static ThreadLocal<Connection>threadLocal
            =new ThreadLocal<>();
    public static final String USER="root";
    public static final String PASSWORD="123456";
    public static final String URL="jdbc:mysql://localhost:3306/test";

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void closeConn(){
        Connection conn = threadLocal.get();
        if (conn!=null){
            try {
                if (!conn.getAutoCommit()){
                conn.commit();}
                conn.close();
                threadLocal.remove();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
    public static void begin(){
        Connection conn=getConn();
        try {
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static Connection getConn() {
        try {
            Connection conn = threadLocal.get();
            if (conn == null) {
                conn = DriverManager
                        .getConnection(URL, USER, PASSWORD);
                threadLocal.set(conn);
            }
            return conn;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}



